package com.yenlien.traceyun.usercenter.dao;

import com.yenlien.traceyun.usercenter.entity.User;
import com.yenlien.traceyun.webase.dao.BaseJpaDao;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-03-04
 * @description:
 **/
public interface UserDao extends BaseJpaDao<User> {
    User findById(String id);



    @Query(value = "select u from User u where u.phone=?1 and u.phone is not null and u.phone <>''")
    public User findByPhone(String phone);

    List<User> getByPhone(String phone);

    @Query(value = "select u from User u where u.email=?1 and u.email is not null and u.email <>''")
    public User findByEmail(String email);

    List<User> getByEmail(String email);

    @Query(value = "select u from User u where u.username=?1 and u.username is not null and u.username <>''")
    public User findByUsername(String username);

    List<User> getByUsername(String username);

    List<User> findByDepartmentIdAndUserType(String id, User.UserType type);

    @Query(value = "select u from User u where u.companyId=?1 and u.userType='COMMON'")
    List<User> findByCompanyId(String companyId);

    @Query(value = "select u from User u where u.companyId=?1 and u.userType='COMMON' and u.name LIKE CONCAT('%',?2,'%')")
    List<User> findByCompanyIdAndName(String companyId, String name);

    @Query(value = "select u from User u where u.companyId=?1 and u.userType='COMPANY'")
    User findCompanyCount(String companyId);

    List<User> findByCreatetimeBetween(Date createtime, Date createtime2);

    List<User> findByCompanyIdIn(List companyId);

    @Query(value = "select count(id) from t_user where company_id=?1", nativeQuery = true)
    int userNum(String companyId);

    @Query(value = "SELECT u.* FROM t_user u WHERE EXISTS (SELECT id FROM t_company c WHERE (parent_id = ?1 OR id = ?1) AND u.company_id = c.id)", nativeQuery = true)
    List<User> getAllUser(String companyId);

    @Query(value = "SELECT * FROM t_user WHERE phone = ?1", nativeQuery = true)
    User findPhone(String phone);

    @Transactional
    @Modifying
    @Query(value = "update t_user set company_id=?2 where id=?1", nativeQuery = true)
    Integer updateCompanyId(String id, String companyId);

    User findByLoginId(String id);
}
